package com.awesome.javademo.threads.thread.future;

import com.awesome.common.util.log.ShowLogUtil;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Created by Alice on 2021/6/7
 */
public class FutureTaskExample {
    public static void main() {
        MyCallable callable1 = new MyCallable(1000);                       // 要执行的任务
        MyCallable callable2 = new MyCallable(2000);

        FutureTask<String> futureTask1 = new FutureTask<String>(callable1);// 将Callable写的任务封装到一个由执行者调度的FutureTask对象
        FutureTask<String> futureTask2 = new FutureTask<String>(callable2);

        ExecutorService executor = Executors.newFixedThreadPool(2);        // 创建线程池并返回ExecutorService实例
        executor.execute(futureTask1);
        executor.execute(futureTask2);

        // 重要api
        // isDone是否已执行完毕
        // get执行完成，返回返回值
        // get(timeout,TimeUnit)timeout时间内执行完成，返回返回值
        while (true) {
            try {
                //  两个任务都完成
                if (futureTask1.isDone() && futureTask2.isDone()) {
                    ShowLogUtil.info("Done");
                    // 关闭线程池和服务
                    executor.shutdown();
                    return;
                }

                // 任务1没有完成，会阻塞
                if (!futureTask1.isDone()) {
                    ShowLogUtil.info("FutureTask1 Done，threadName=" + futureTask1.get());
                }

                ShowLogUtil.info("Waiting for FutureTask2 to complete");

                // 200毫秒内没有执行完，返回null
                String s = futureTask2.get(200L, TimeUnit.MILLISECONDS);
                if (s != null) {
                    ShowLogUtil.info("FutureTask2 Done，threadName=" + s);
                }
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
            }
        }

    }
}